<?php
namespace app\common\model;

use think\Model;
use think\Db;
use \app\common\libs\WeixinHepler;
use \app\common\model\WXLogs;

class WXUser extends Model
{
    protected $table = 'weixin_user';
    
    const SUBSCRIBE_STATUS = 1;
    const UNSUBSCRIBE_STATUS = 2;

    /*
	   * 用户关注
     * $from_openid 公众号id
     */
  	public function subscribe($subscribe_data=[], $from_openid='') {
  		$count = $this->where(array('username' => $subscribe_data['openid']))->count();

  		$data = array(
            'username' => $subscribe_data['openid'],//openid用户唯一标识
            'nickname' => $subscribe_data['nickname'],//用户昵称
            'sex' => $subscribe_data['sex'],//性别, 1代表男,2代表女,0代表未知
            'city' => $subscribe_data['city'],//所在城市
            'province' => $subscribe_data['province'],//所在省
            'headimgurl' => $subscribe_data['headimgurl'],//头像图片url
            'status' => $this::SUBSCRIBE_STATUS,//状态,1代码已关注,2代表已取消
        );

        if($count) {
        	$this->where('username', $subscribe_data['openid'])->update($data);
        }else {
        	$this->save($data);
        }

        $log_data['from_openid'] = $from_openid;
        $log_data['username'] = $subscribe_data['openid'];
        $log_data['c_type'] = 'subscribe';

        $logs_model = new WXLogs;
        $logs_model->data($log_data)->save();
  	}

  	/*
	 * 用户取消
  	 */
  	public function unsubscribe($FromUserName, $from_openid='') {
      $this->where('username', $FromUserName)->update(['status'=>$this::UNSUBSCRIBE_STATUS]);

        $data['username'] = $FromUserName;
        $data['c_type'] = 'unsubscribe';
        $data['from_openid'] = $from_openid;
        $logs_model = new WXLogs;
        $logs_model->data($data)->save();
    }
}